﻿/*
 * 泛依ORMJS代码
 * 范叶勇
 * fyybuilder.com
 * 2022-08-12 10:50:00
 * Copyright (c) since2015 泛依软件
 */
function tbl_queryhash_load() {
    queryhash = new tbl_queryhash();
    queryhash.parseFromLocation();
    tbl_update_form_byqueryhash();
}

function tbl_update_form_byqueryhash() {
    if (queryhash.HasHash()) {
        $('#txt_query').val(queryhash.keyword);
    }
}

function tbl_update_queryhash_byform() {
    queryhash.keyword = $('#txt_query').val();
    console.log(queryhash);
    queryhash.updateLocation();
}

function query_tbl_byhash() {
    tbl_queryhash_load();
    query_tbl();
}

function query_tbl() {
    tbl_update_queryhash_byform();
    var json_text = "{'KEY':'" + $('#txt_query').val() + "','TYPE':'" + queryhash.type + "','TBLS':'" + queryhash.tbls+"'}";
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/QueryTBL",
        contentType: 'application/json',
        data: json_text,
        success: function (result) {
            if (result.success == false) {
                $('.map-right code').html(result.message);
                return;
            }

            console.log(result);
            var rowcount = $('.tbl-container .tbl-item').length;
            for (var i = 0; i < rowcount - 1; i++) {
                $('.tbl-container .tbl-item:eq(1)').remove();
            }

            var tblarr=[];
            if (queryhash.tbls != '') {
                tblarr = queryhash.tbls.split(',');
            }

            $.each(result.data, function (index, item) {
                //console.log(item);
                var newitem = $('.tbl-container .tbl-item:eq(0)').clone();
                var cbx = newitem.find("input");
                cbx.val(item.tableName);
                if ($.inArray($(cbx).val(), tblarr) > -1) {
                    $(cbx).prop('checked', true);
                }
                var xh = newitem.find("span");
                xh.text((index + 1) + '.');
                var a_tbl = newitem.find("a");
                a_tbl.text(item.tableName);
                a_tbl.bind('click', { NAME: item.tableName }, function (event) {
                    mapper_tbl(event.data.NAME);
                    return false;
                });
                newitem.removeClass('hide');
                $('.tbl-container').append(newitem);
            });

            $('.map-right code').html(result.obj);
            hljs.initHighlightingOnLoad();
        }
    });
}

function mapper_db() {
    var tbls = "";
    $("input[name='tbl']:checked").each(function (i) {
        if (tbls == "") {
            tbls += $(this).val();
        } else {
            tbls += "," + $(this).val();
        }
    });
    queryhash.type = '1';
    queryhash.tbls = tbls;
    queryhash.updateLocation();
    var json_text = "{'TBLS':'" + tbls + "'}";
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/MapperDB",
        contentType: 'application/json',
        data: json_text,
        success: function (result) {
            if (result.success == false) {
                $('.map-right code').html(result.message);
                return;
            }

            $('.map-right code').html(result.data);
            hljs.initHighlightingOnLoad();
        }
    });
}

function mapper_tbl(tbl) {
    queryhash.type = '2';
    queryhash.tbls = tbl;
    queryhash.updateLocation();
    var json_text = "{'TBLS':'" + tbl + "'}";
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/MapperTBL",
        contentType: 'application/json',
        data: json_text,
        success: function (result) {
            if (result.success == false) {
                return;
            }

            $('.map-right code').html(result.data);
            hljs.initHighlightingOnLoad();
        }
    });
}

function query_cfgdb() {
    var json_text = "{}";
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/QueryCfgDB",
        contentType: 'application/json',
        data: json_text,
        success: function (result) {
            if (result.success == false) {
                return;
            }
            console.log(result.data);
            var rowcount = $('table tr').length;
            for (var i = 0; i < rowcount - 2; i++) {
                $('table tr:eq(2)').remove();
            }

            $.each(result.data, function (index, item) {
                //console.log(item);
                var newtr = $('table tr:eq(1)').clone();
                var tds = newtr.find("td");
                tds.eq(0).html(index + 1);
                tds.eq(1).html(item.ip);
                tds.eq(2).html(item.databaseName);
                tds.eq(3).html(item.databaseType);
                tds.eq(4).html(item.userName);
                tds.eq(5).html(item.password);

                var statusHtml = '';
                if (item.isCurrentDb == '1') {
                    statusHtml = '<span class="f-green-lable">是</span>';
                } else {
                    statusHtml = '<span>否</span>';
                }

                tds.eq(6).html(statusHtml);
                tds.eq(7).html(item.note);
                tds.eq(8).find('.edit').bind('click', { ID: item.id }, function (event) {
                    window.location.href = "dbadd.html?id=" + event.data.ID;
                });
                tds.eq(8).find('.del').bind('click', { ID: item.id }, function (event) {
                    showAskPopup({ id: event.data.ID });
                });
                newtr.removeClass('hide');
                newtr.mouseover(function () {
                    $(this).addClass("over");
                }).mouseout(function () {
                    $(this).removeClass("over");
                });
                $('table').append(newtr);
            });
        }
    });
}

function del(id) {
    var json_text = "{'ID':'" + id + "'}";
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/DelCfgDB",
        contentType: 'application/json',
        data: json_text,
        success: function (result) {
            if (result.success == false) {
                return;
            }

            query_cfgdb();
        }
    });
}

function view_cfgdb() {
    var json = {};
    var id = $.getUrlVar('id');
    json["ID"]=id;
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/ViewCfgDB",
        contentType: 'application/json',
        data: JSON.stringify(json),
        success: function (result) {
            if (result.Success == false) {
                return;
            }

            var obj = result.data;
            $('#txt_ip').val(obj.ip);
            $('#ddl_dbtype').val(obj.databaseType);
            $('#txt_name').val(obj.databaseName);
            $('#txt_username').val(obj.userName);
            $('#txt_pwd').val(obj.password);
            $('#ddl_iscurrent').val(obj.isCurrentDb);
            $('#txt_note').val(obj.note);
        }
    });
}

var old_cfgdb_id = '';
function add_cfgdb() {
    var json = {};
    var id = $.getUrlVar('id');
    if (id == '') {
        if (old_cfgdb_id != '') {
            id = old_cfgdb_id;
        }
    }

    var ip = $('#txt_ip').val();
    if (ip == '') {
        showerr('IP为空！', 2000);
        return;
    }

    json["ID"] = id;
    json["IP"] = ip;
    json["DatabaseType"] = $('#ddl_dbtype').val();
    json["DatabaseName"] = $('#txt_name').val();
    json["UserName"] = $('#txt_username').val();
    json["Password"] = $('#txt_pwd').val();
    json["IsCurrentDb"] = $('#ddl_iscurrent').val();
    json["Note"] = $('#txt_note').val();
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/AddCfgDB",
        contentType: 'application/json',
        data: JSON.stringify(json),
        success: function (result) {
            if (result.Success) {
                showsucc('保存成功！', 3000);
                old_cfgdb_id = result.data;
                return;
            }

            showerr(result.message, 3000);
        }
    });
}

/**
 * 初始化询问对话框
 * @param {any} options
 */
function initAskPopup(options) {
    initAskPopupOptions = options;
    var popupHTML = '';
    popupHTML += "   <div class=\"title\">" + options.title + "</div>";
    popupHTML += "   <div class=\"close\">";
    popupHTML += "       <a href=\"javascript:;\" title=\"关闭\">";
    popupHTML += "          <img src=\"/images/close.png\">";
    popupHTML += "       </a>";
    popupHTML += "   </div>";
    popupHTML += "   <div class=\"form\">";
    popupHTML += "       <div class=\"content\">" + options.content + "</div>";
    popupHTML += "   </div >";
    popupHTML += "   <div class=\"btn\" style=\"display: block; \">";
    popupHTML += "       <input type=\"button\" class=\"f-red-button\" value=\"是\">";
    popupHTML += "       <input type=\"button\" class=\"f-hidden\">";
    popupHTML += "       <input type=\"button\" class=\"f-ret-button\" value=\"否\">";
    popupHTML += "   </div>";
    $("#" + options.id).html(popupHTML);
    if (options.close != undefined) {
        $('#' + options.id).find('.close a').bind('click', {}, function (event) {
            options.close();
            hideAskPopup();
        });

        $('#' + options.id).find('.btn .f-ret-button').bind('click', {}, function (event) {
            options.close();
            hideAskPopup();
        });
    }

    if (options.ok != undefined) {
        $('#' + options.id).find('.btn .f-red-button').bind('click', {}, function (event) {
            options.ok(options.props);
            hideAskPopup();
        });
    }
}

/**
 *  显示询问框
 * @param {any} props
 */
function showAskPopup(props) {
    console.log(initAskPopupOptions);
    initAskPopupOptions.props = props;
    $('#' + initAskPopupOptions.id).css('display', 'block');
    $('.f-popup-shade').css('display', 'block');
}

/**
 * 隐藏询问框
 * */
function hideAskPopup() {
    $('#' + initAskPopupOptions.id).css('display', 'none');
    $('.f-popup-shade').css('display', 'none');
}

/**
 * 导出实体代码zip包
 * */
function export_cszip() {
    var tbls = "";
    $("input[name='tbl']:checked").each(function (i) {
        if (tbls == "") {
            tbls += $(this).val();
        } else {
            tbls += "," + $(this).val();
        }
    });

    var json = { TBLS: tbls };
    $.ajax({
        type: "POST",
        async: "false",
        url: "/api/Mapper/Export",
        contentType: 'application/json',
        data: JSON.stringify(json),
        success: function (result) {
            if (!result.success) {
                showerr(result.message, 3000);
                return;
            }

            window.location.href = result.data;
        }
    });
}

function showAbout() {
    var aboutTxt = "/********************************v1.0.0********************************/\r\n";
    aboutTxt += "这是泛依系列软件的.NET ORM框架。支持mysql、oracle、sqlite、sqlserver数据库。\r\n";
    aboutTxt += "业务合作(微信):13485679260\r\n";
    aboutTxt += "联系邮箱:fyysoft@126.com\r\n";
    aboutTxt += "在线系统：fanyeyong.com      fyybuilder.com\r\n";
    aboutTxt += "/*****************************使用方法如下*****************************/\r\n";
    aboutTxt += "Test_Dbcontext test_Dbcontext = new Test_Dbcontext(此处填连接字符串) //定义数据库上下文对象\r\n";
    aboutTxt += "PagedQuery pagedQuery = new PagedQuery(); //定义分页查询对象\r\n";
    aboutTxt += "pagedQuery.IdField=\"id\"; //主键字段\r\n";
    aboutTxt += "pagedQuery.PageIndex=1; //分页索引\r\n";
    aboutTxt += "pagedQuery.SortClause=\"id desc\"; //排序语句\r\n";
    aboutTxt += "pagedQuery.PageSize=20; 分页尺寸\r\n";
    aboutTxt += "test_Dbcontext.T.FetchPageList(T, pagedQuery); //获取分页结果列表\r\n";
    aboutTxt += "test_Dbcontext.T.FetchCount(pagedQuery); //获取记录总数\r\n";
    aboutTxt += "test_Dbcontext.T.Fetch(id); //查记录（此方法有多个重载） \r\n";
    aboutTxt += "test_Dbcontext.T.Insert(t); //添加记录 \r\n";
    aboutTxt += "test_Dbcontext.T.Update(t); //编辑记录 \r\n";
    aboutTxt += "test_Dbcontext.T.Delete(id); //删除记录 \r\n";
    aboutTxt += "NHashtable ht = new NHashtable(); //参数化查询 \r\n";
    aboutTxt += "string sql=\"select * from T where key like @key\"; \r\n";
    aboutTxt += "ht.Add(\"key\", \"%关键字%\"); \r\n";
    aboutTxt += "List<T> list=test_Dbcontext.T.FetchList(sql, ht); //获取查询结果列表 \r\n";
    aboutTxt += "List<T> list=test_Dbcontext.T.FetchList(p=>p.code.Like(\"%key%\")); //lambda表达式查询 \r\n";
    aboutTxt += "List<T> list=test_Dbcontext.T.FetchListWithStoreProc('proc_name'); //根据存储过程获取列表（可带NHashtable） \r\n";
    aboutTxt += "int result=test_Dbcontext.FetchBaseDbLogic().RunProcedure('proc_name',ht); //执行带参数的存储过程 \r\n";
    aboutTxt += "ExecuteResult er=test_Dbcontext.FetchBaseDbLogic().BeginTransaction(); //开始事务 \r\n";
    aboutTxt += "er=test_Dbcontext.T.InsertWithTrans(t,er.DbTransaction); //添加事务 \r\n";
    aboutTxt += "er=test_Dbcontext.T.UpdateWithTrans(t,er.DbTransaction); //编辑事务 \r\n";
    $('.map-right code').html(aboutTxt);
    hljs.initHighlightingOnLoad();
}

showsucc = function (message, life) {
    time = life;
    if ($("#tip_message").text().length > 0) {
        var msg = "<span>" + message + "</span>";
        $("#tip_message").empty().append(msg);
    } else {
        var msg = "<div id='tip_message'><span>" + message + "</span></div>";
        $("body").append(msg);
    }

    $("#tip_message").fadeIn(time);
    setTimeout(tip_fadOut, time, time);
};

showerr = function (message, life) {
    showsucc(message, life);
    $("#tip_message span").addClass("error");
};

function tip_fadOut(time) {
    $("#tip_message").fadeOut(time);
}

$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    },
    addUrlVar: function (url, name, value) {
        var r = url;
        if (r != null && r != 'undefined' && r != "") {
            value = encodeURIComponent(value);
            var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
            var tmp = name + "=" + value;
            if (url.match(reg) != null) {
                r = url.replace(eval(reg), tmp);
            }
            else {
                if (url.match("[\?]")) {
                    r = url + "&" + tmp;
                } else {
                    r = url + "?" + tmp;
                }
            }
        }

        location.replace(r);
        //return r;
    }
});